<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" rel="stylesheet">
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script crossorigin="anonymous"
            integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
            src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
<!--   提示框-->

    <script type="text/javascript" th:src="@{/toastr/toastr.js}" ></script>
    <link  th:href="@{/toastr/toastr.min.css}"  rel="stylesheet" />
    <link rel="stylesheet" th:href="@{/admin/admin.css}" type="text/css" />
    <script type="text/javascript" th:src="@{/js/echarts.min.js}" ></script>
</head>

<body>
<h1  align="center">CRUD</h1>
    <table>
        <th><button class="btn btn-default" id="add">增加</button></th>
        <th><button class="btn btn-default" th:onclick="getExcel()">点击我下载表格</button></th>



    </table>
<div class="row">
        <!-- column -->
        <div class="col-lg-12">
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                            <tr >
                                <th>ID</th>
                                <th>员工名称</th>
                                <th>性别</th>
                                <th>年龄</th>
                                <th>职位</th>
                                <th>操作</th>
                            </tr>
                            </thead>

                        <tbody id="tbody">
                        <tr th:each="user:${pages.list}" >

                            <td  th:text="${user.id}"/>
                            <td  th:text="${user.username}"/>
                            <td  th:text="${user.sex}==0?'男':'女'"/>
                            <td  th:text="${user.age}"/>
                            <td  th:text="${user.position}==1?'职员':'经理'"/>

                            <td>
                                <input class="btn btn-primary"  type="button"  value="编辑" th:onclick="'javascript:edit('+${user.id}+')'" ></input>
                                <input class="btn btn-danger"  type="button" value="删除"  th:onclick="'javascript:del('+${user.id}+')'" ></input>

                            </td>
                        </tr>
                        </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!--         分页导航条-->
    <div class="pagination">
        <a id="shouye" th:href="@{/}"><span  class="btn-page btn-default" th:unless="${pages.pageNum} eq 1">首页</span></a>
        <a th:href="@{/(pageNum=${pages.hasPreviousPage}?${pages.prePage}:1)}"><span
                class="btn-page btn-default" th:unless="${pages.pageNum} eq 1">上一页</span></a>
        <!--            <-- 遍历导航页 &ndash;&gt;-->
        <a th:each="page,pageStat:${pages.navigatepageNums}"
           th:href="@{/(pageNum=${page})}">
                                        <span th:if="${page}==${pages.pageNum}">
                                            <span class="btn-page btn-active" th:text="${page}"></span>
                                        </span>
            <span th:if="${page}!=${pages.pageNum}">
                                            <span class="btn-page btn-default" th:text="${page}"></span>
                                        </span>
        </a>
        <!--            <-- 导航页 &ndash;&gt;-->

        <a th:href="@{/(pageNum=${pages.hasNextPage}?${pages.nextPage}:${pages.pages})}"><span
                class="btn-page btn-default" th:unless="${pages.pageNum} eq ${pages.pages}">下一页</span></a>
        <a th:href="@{/(pageNum=${pages.pages})}"><span class="btn-page btn-default" th:unless="${pages.pageNum} eq ${pages.pages}">尾页</span></a>
    </div>
    <div class="row">
        <div class="col-md-6">
            当前第[[${pages.pageNum}]]页，共[[${pages.pages}]]页，共[[${pages.total}]]条记录 </div>
    </div>


<!--  Modal员工修改模态框-->
<div class="modal fade" id="empUpdataModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel2">员工修改</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="empUpdataModal_from">
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">员工名称</label>
                        <div class="col-sm-10">
                            <input type="text" name="username" class="form-control "
                                   id="username_updata"  value=""/>
                            <span class="help-block"></span>
                        </div>

                    </div>
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">性别</label>
                        <select id="sex_updata" >
                            <option value="0">男</option>
                            <option value="1">女</option>
                        </select>
                    </div>

                    <div class="modal-body">
                        <form class="form-horizontal">
                            <div class="form-group">
                                <label  class="col-sm-2 control-label">年龄</label>
                                <div class="col-sm-10">
                                    <input type="text" name="age" class="form-control "
                                           nblur=""  id="age_updata" value="" />
                                    <span class="help-block"></span>
                                </div>

                            </div>

                            <div class="form-group">
                                <label  class="col-sm-2 control-label">职位</label>
                                <select id="pt_updata" >
                                    <option value="1">职员</option>
                                    <option value="2">经理</option>
                                </select>
                            </div>
                        </form>

                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal" id="emp_exit_btn_updata">取消</button>
                        <button type="button" class="btn btn-primary" id="emp_updae_btn">更新</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!--  Modal员工添加模态框-->
<div class="modal fade" id="empAddModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">员工添加</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="empAddModal_from">
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">员工名称</label>
                        <div class="col-sm-10">
                            <input type="text" name="username" class="form-control "
                                   nblur="" id="username" placeholder="必填项"/>
                            <span class="help-block"></span>
                        </div>

                    </div>
                    <div class="form-group">
                        <label  class="col-sm-2 control-label">性别</label>
                        <select id="sex" >
                            <option value="0">男</option>
                            <option value="1">女</option>
                        </select>
                    </div>

                    <div class="modal-body">
                        <form class="form-horizontal" id="">
                            <div class="form-group">
                                <label  class="col-sm-2 control-label">年龄</label>
                                <div class="col-sm-10">
                                    <input type="text" name="age" class="form-control "
                                           nblur="" id="age" placeholder="必填项"/>
                                    <span class="help-block"></span>
                                </div>

                            </div>

                            <div class="form-group">
                                <label  class="col-sm-2 control-label">职位</label>
                                <select id="pt" >
                                    <option value="1">经理</option>
                                    <option value="2">职员</option>
                                </select>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal" id="emp_exit_btn">取消</button>
                        <button type="button" class="btn btn-primary" id="emp_save_btn">更新</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

</div>
<div >
<div id="main" style="width: 600px;height:400px; float: left;"></div>
    <div id="main2" style="width: 600px;height:400px; float: left;"></div>
    </div>

</body>



<script  type="text/javascript" th:inline="javascript" >


    toastr.options.positionClass = 'toast-top-center';


    //完整重置弹出框表单
    function reset_form(ele){
        //重置表单
        $(ele)[0].reset();
        //清空表单样式
        $(ele).find("*").removeClass("has-error has-success");
        $(ele).find(".help-block").text("");

    }

    // 点击新增
    $("#add").click(function () {

        $("#empAddModal").modal({
            //清除表单数据（表单完整重置（表单的数据，表单的样式））
            backdrop:"static"
        });

    });

      // 保存
    $("#emp_save_btn").click(function(){

        parArr = {};
        var username = $("#username").val().replace(/(^\s*)|(\s*$)/g, "");
        parArr.username = username;
        var age = $("#age").val().replace(/(^\s*)|(\s*$)/g, "");
        parArr.age = age;
        var sex = $("#sex").val().replace(/(^\s*)|(\s*$)/g, "");
        parArr.sex = sex;
        var position = $("#pt").val().replace(/(^\s*)|(\s*$)/g, "");
        parArr.position = position;
        var params = JSON.stringify(parArr);

        if(username==null ||  username=="" ||
            age==null ||  age=="" ||
            sex==null ||  sex=="" ||
            position==null ||  position==""
        ){
            toastr.error('必填项不能为空');
        }else{


            $.ajax({
                url:"/addUser",
                type:"POST",
                data:{"username":username,"sex":sex,"age":age,"position":position},
                success:function(data) {
                    //alert(result.msg);
                    if (data.type=="success") {
                        toastr.success('保存数据成功');
                        //员工保存成功；
                        //1、关闭模态框
                        $("#empAddModal").modal('hide');
                        setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                            window.location.reload();//页面刷新
                        },1000);

                    }else {
                        toastr.error('保存数据失败');

                    }
                }

            })
        }
    });


     // 根据id查询
    function edit(id) {


       $("#empUpdataModal").modal({
            backdrop:"static"
        });
        $.ajax({
            url:"/UserById/"+id,
            type:"get",
            success:function(data) {
                $("#username_updata").attr("value",data.username);
                  $("#age_updata").attr("value",data.age);
                  if (data.sex == 0){
                      $("#sex_updata option:eq(0)").attr("selected","selected");
                      // $("#sex_updata option:first").attr("text","男").attr("selected",true);
                  }else {
                      $("#sex_updata option:eq(1)").attr("selected","selected");
                  }
                if (data.position == 1){
                    $("#pt_updata option:eq(0)").attr("selected","selected");
                }else {
                    $("#pt_updata option:eq(1)").attr("selected","selected");
                }
                // $("#pt_updata").attr("value",data.position);
            }

        });


        window.n = id;
    }

        // 修改数据
    $("#emp_updae_btn").click(function () {


        var id=n;

        var username = $("#username_updata").val().replace(/(^\s*)|(\s*$)/g, "");

        var age = $("#age_updata").val().replace(/(^\s*)|(\s*$)/g, "");

        var sex = $("#sex_updata").val().replace(/(^\s*)|(\s*$)/g, "");

        var position = $("#pt_updata").val().replace(/(^\s*)|(\s*$)/g, "");


        if(username==null ||  username=="" ||
            age==null ||  age=="" ||
            sex==null ||  sex=="" ||
            position==null ||  position==""
        ){
            toastr.error('必填项不能为空');
        }
        else{
        $.ajax({
            type: "post",
            url: "/updateUser",
            data: {"id":id,"username":username,"sex":sex,"age":age,"position":position},
            success: function(data){
                if(data.type=="success"){
                    toastr.success('修改数据成功');
                    setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                        window.location.reload();//页面刷新
                    },1000);

                }else{
                    toastr.error('修改数据失败');
                }
            }
        });
        }
    });



    function del(id){
        if(window.confirm('你确定要刪除嗎？')){
            $.ajax({
                type: "get",
                url: "/delUser/"+id,
                dataType: "json",
                data: "id="+id,
                success: function(data){
                    if(data.type=="success"){
                        toastr.success('删除数据成功');
                        setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                            window.location.reload();//页面刷新
                        },1000);

                    }else{
                        toastr.error('删除数据失败');
                    }
                }
            });

            return true;
        }else{

            return false;
        }

    }

        //excl导出
    function getExcel(){
        var myDate = new Date();
        var mytime=myDate.toLocaleTimeString();
        var sex1=0;
        var sex2=0;
        var position1=0;
        var position2=0;
        $.ajax({
            url: "/listUserExc",
            type: "get",
            success: function (data) {

                let str = `id,姓名,性别,年龄,职位\n`;
                //增加\t为了不让表格显示科学计数法或者其他格式
                for(let i = 0; i < data.length; i++){
                    for(let item in data[i]){
                        str+=`${data[i][item] + '\t'},`;
                    }
                    str+='\n';


                }

                //encodeURIComponent解决中文乱码， \ufeff是 ""
                let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
                //通过创建a标签实现
                let link = document.createElement("a");
                link.href = uri;
                //对下载的文件命名
                link.download =  mytime+"信息统计统计.csv";
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);


            }
        });
        }

    //页面刷新完时调用
    $(document).ready(function(){
        var sex1=0;
        var sex2=0;
        var position1=0;
        var position2=0;
        $.ajax({
            url: "/listUserExc",
            type: "get",
            success: function (data) {

                for(let i = 0; i < data.length; i++){
                    if (data[i].sex == '0'){
                        sex1++;

                    }else if (data[i].sex == "1"){
                        sex2++;

                    }

                    if (data[i].position == "1"){
                        position1++;

                    }else if (data[i].position == "2"){
                        position2++;

                    }

                }

                // alert(sex1+"-"+sex2+"-"+position1+"-"+position2);


    var myChart = echarts.init(document.getElementById('main'));
    option = {
        backgroundColor: '#2c343c',

        title: {
            text: '男女比例表',
            left: 'center',
            top: 20,
            textStyle: {
                color: '#ccc'
            }
        },

        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
        },

        visualMap: {
            show: false,
            min: 80,
            max: 600,
            inRange: {
                colorLightness: [0, 1]
            }
        },
        series: [
            {
                name: '数据来源数据库',
                type: 'pie',
                radius: '55%',
                center: ['50%', '50%'],
                data: [

                    {value: sex1, name: '男性'},
                    {value: sex2, name: '女性'}
                ].sort(function (a, b) { return a.value - b.value; }),
                roseType: 'radius',
                label: {
                    color: 'rgba(255, 255, 255, 0.3)'
                },
                labelLine: {
                    lineStyle: {
                        color: 'rgba(255, 255, 255, 0.3)'
                    },
                    smooth: 0.2,
                    length: 10,
                    length2: 20
                },
                itemStyle: {
                    color: '#c23531',
                    shadowBlur: 200,
                    shadowColor: 'rgba(255,69,0, 0.7)'
                },

                animationType: 'scale',
                animationEasing: 'elasticOut',
                animationDelay: function (idx) {
                    return Math.random() * 200;
                }
            }
        ]
    };
    // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);

    var myChart2 = echarts.init(document.getElementById('main2'));
    option = {

        title: {
            text: '职工比例表',
            left: 'center',
            top: 20,
            textStyle: {
                color: '#000000'
            }
        },

        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            left: 10,
            data: ['经理', '职员']
        },
        series: [
            {
                name: '数据来源数据库',
                type: 'pie',
                radius: ['50%', '70%'],
                avoidLabelOverlap: false,
                label: {
                    normal: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        show: true,
                        textStyle: {
                            fontSize: '30',
                            fontWeight: 'bold'
                        }
                    }
                },
                labelLine: {
                    normal: {
                        show: false
                    }
                },
                data: [
                    {value: position1, name: '经理'},
                    {value: position2, name: '职员'}
                ]
            }
        ]
    };
    // 使用刚指定的配置项和数据显示图表。
    myChart2.setOption(option);
    // });



            }
        });
    });

</script>


</html>